package logic

import (
	"context"
	"fmt"
	"modbus/rpcServer/internal/svc"
	"modbus/rpcServer/types/iotrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetDeviceReqLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSetDeviceReqLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetDeviceReqLogic {
	return &SetDeviceReqLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

const (
	COIL_OFF = 00
	COIL_ON  = 0xFF00
)

func (l *SetDeviceReqLogic) SetDeviceReq(in *iotrpc.SetDeviceReq) (*iotrpc.SetDeviceRsp, error) {
	// todo: add your logic here and delete this line
	table := *l.svcCtx.DevMap
	if exists := table[in.DevName]; exists != nil {
		switch in.Type {
		case 1:
			switch in.Val {
			case 0:
				exists.CoilRegWrite(uint16(in.RegAddr), COIL_OFF)
			case 1:
				exists.CoilRegWrite(uint16(in.RegAddr), COIL_ON)
			}
		case 2:
			ratio := exists.RegTable.HoldingReg[int(in.RegAddr)].Ratio
			exists.HoldingRegWrite(uint16(in.RegAddr), uint16(in.Val/ratio))
		}
	} else {
		fmt.Println(exists)
	}

	rsp := iotrpc.SetDeviceRsp{}
	rsp.Res = "ok"
	return &rsp, nil
}
